/* ---------------------------------------------------------------------------------------------
 *
 *            Capital Alliance Software Confidential Proprietary
 *            (c) Copyright CAS 201{x}, All Rights Reserved
 *                          www.pekall.com
 *
 * ----------------------------------------------------------------------------------------------
 */

package com.pekall.todo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.pekall.todo.model.ToDoTasks;
import com.pekall.todo.util.SQLiteOperate;

/**
 * @author LeiKang 待办事件操作类
 */
public class ShowScreen extends Activity implements OnClickListener {
    // private static final String TAG = MainScreen.class.getCanonicalName();
    private static String[] arrLevel = {
            "低", "中", "高"
    };

    private static String[] arrState = {
            "未完成", "已完成"
    };

    private String NO_TITLE = "无主题";

    // private TextView mSpannerLevel;

    // private TextView mSpannerState;

    private ArrayAdapter<String> mAdapter;

    private TextView mStartDateBtn;

    private TextView mStartTimeBtn;

    private TextView mEndDateBtn;

    private TextView mEndTimeBtn;

    // private ImageButton mBackBtn;
    private TextView mTitleView;

    private TextView mTitle;

    private TextView mDetail;

    private Time mStartTime;

    private Time mEndTime;

    private ToDoTasks mToDoTasks;

    private Context context;

    private ToDoTasks initTodoTasks;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.showscreen);
        context = this;
        /**
         * 设置事项级别与状态
         */
        // mSpannerLevel = (TextView) findViewById(R.id.level);
        // mSpannerState = (TextView) findViewById(R.id.state);
        mStartDateBtn = (TextView) findViewById(R.id.startDateBtn);
        mStartTimeBtn = (TextView) findViewById(R.id.startTimeBtn);
        mEndDateBtn = (TextView) findViewById(R.id.endDateBtn);
        mEndTimeBtn = (TextView) findViewById(R.id.endTimeBtn);
        // mSaveBtn = (Button) findViewById(R.id.save);
        // mGiveupBtn = (Button) findViewById(R.id.giveup);
        // mBackBtn = (ImageButton) findViewById(R.id.backhome);
        mTitleView = (TextView) findViewById(R.id.titleText);
        mTitle = (TextView) findViewById(R.id.title);
        mDetail = (TextView) findViewById(R.id.detail);
        init();
    }

    /*
     * (non-Javadoc)
     * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        super.onKeyDown(keyCode, event);
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            saveInfo();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void onClick(View v) {
        if (v.getId() == R.id.save) {
            saveInfo();
        } else if (v.getId() == R.id.giveup) {
            back();
        }
        // else if (v.getId() == R.id.backhome) {
        // saveInfo();
        // }
    }

    private void init() {
        Intent intent = getIntent();
        mToDoTasks = (ToDoTasks) intent.getSerializableExtra("todotasks_key");
        initTodoTasks = new ToDoTasks();
        initTodoTasks.setBegin(mToDoTasks.getBegin());
        initTodoTasks.setNotes(mToDoTasks.getNotes());
        initTodoTasks.setOver(mToDoTasks.getOver());
        initTodoTasks.setTitle(mToDoTasks.getTitle());
        initTodoTasks.setState(mToDoTasks.getState());
        initTodoTasks.setType(mToDoTasks.getType());
        initTodoTasks.setBegin(mToDoTasks.getBegin());
        mStartTime = new Time();
        mEndTime = new Time();
        // New event
        if (Time.isEpoch(mStartTime) && Time.isEpoch(mEndTime)) {
            mStartTime.setToNow();
            mStartTime.second = 0;
            int minute = mStartTime.minute;
            if (minute == 0) {
            } else if (minute > 0 && minute <= 30) {
                mStartTime.minute = 30;
            } else {
                mStartTime.minute = 0;
                mStartTime.hour += 1;
            }
            long startMillis = mStartTime.normalize(true /* ignore isDst */);
            mEndTime.set(startMillis + DateUtils.HOUR_IN_MILLIS);
        }
        // 新建事件
        if (mToDoTasks.getId() == 0) {
            mTitleView.setText(R.string._new_task);
        } else {
            mStartTime.set(mToDoTasks.getBegin());
            mEndTime.set(mToDoTasks.getOver());
            mTitleView.setText(R.string._edit_task);
        }
        populateWhen();
        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrLevel);
        mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // mSpannerLevel.setAdapter(mAdapter);
        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrState);
        mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // mSpannerState.setAdapter(mAdapter);
        // mSpannerLevel.setSelection(mToDoTasks.getType());
        // mSpannerState.setSelection(mToDoTasks.getState());
        // mSpannerLevel.setOnItemSelectedListener(new OnItemSelectedListener()
        // {
        // public void onItemSelected(AdapterView<?> arg0, View arg1,
        // int arg2, long arg3) {
        // mToDoTasks.setType(arg2);
        // }
        //
        // public void onNothingSelected(AdapterView<?> arg0) {
        // }
        // });
        // mSpannerState.setOnItemSelectedListener(new OnItemSelectedListener()
        // {
        // public void onItemSelected(AdapterView<?> arg0, View arg1,
        // int arg2, long arg3) {
        // mToDoTasks.setState(arg2);
        // }
        //
        // public void onNothingSelected(AdapterView<?> arg0) {
        // }
        // });
        mStartDateBtn.setOnClickListener(new DateClickListener(mStartTime));
        mStartTimeBtn.setOnClickListener(new TimeClickListener(mStartTime));
        mEndDateBtn.setOnClickListener(new DateClickListener(mEndTime));
        mEndTimeBtn.setOnClickListener(new TimeClickListener(mEndTime));
        // mSaveBtn.setOnClickListener(this);
        // mGiveupBtn.setOnClickListener(this);
        // mBackBtn.setOnClickListener(this);
        mTitle.setText(mToDoTasks.getTitle());
        mDetail.setText(mToDoTasks.getNotes());
    }

    // 点击返回和保存按钮
    private void saveInfo() {

        String title = mTitle.getText().toString();
        String notes = mDetail.getText().toString();
        mToDoTasks.setTitle(title);
        mToDoTasks.setNotes(notes);
        mToDoTasks.setBegin(mStartTime.toMillis(false));
        mToDoTasks.setOver(mEndTime.toMillis(false));
        boolean ischanged = (initTodoTasks.getBegin() == mToDoTasks.getBegin())
                && (initTodoTasks.getNotes().equals(mToDoTasks.getNotes()))
                && (initTodoTasks.getOver() == mToDoTasks.getOver())
                && (initTodoTasks.getState() == mToDoTasks.getState())
                && (initTodoTasks.getType() == mToDoTasks.getType())
                && (initTodoTasks.getTitle().equals(mToDoTasks.getTitle()));

        if (!ischanged) {
            if (title.equals("") && notes.equals("")) {
                Toast.makeText(this, R.string._empty_save, Toast.LENGTH_SHORT).show();
            }
            if (title.equals("") && (!notes.equals(""))) {
                mToDoTasks.setTitle(NO_TITLE);
            }
            if (!title.equals("") || !notes.equals("")) {
                mStartTime.setToNow();
                if (mToDoTasks.getId() == 0)
                    mToDoTasks.setCreated(mStartTime.toMillis(false));
                mToDoTasks.setModified(mStartTime.toMillis(false));
                SQLiteOperate sql = new SQLiteOperate(this);
                sql.saveOrUpdate(mToDoTasks);
                Toast.makeText(this, R.string._ok_save, Toast.LENGTH_SHORT).show();
            }
        }
        back();

    }

    private void delete() {
        Dialog dialog = new AlertDialog.Builder(this).setIcon(android.R.drawable.btn_star)
                .setTitle(R.string._delete).setMessage(R.string._delete_message).setNegativeButton(
                        R.string._cancle, null).setNeutralButton(R.string._ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                SQLiteOperate sql = new SQLiteOperate(context);
                                if (mToDoTasks.getId() != 0)
                                    sql.deleteById(mToDoTasks.getId());
                                finish();
                            }
                        }).create();
        dialog.show();
    }

    // 点击放弃按钮
    private void back() {
        this.finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, Menu.FIRST + 1, Menu.NONE, R.string._save)
                .setIcon(R.drawable.cmcc_toolbar_save);
        if (mToDoTasks.getId() != 0)
            menu.add(0, Menu.FIRST + 2, Menu.NONE, R.string._delete).setIcon(
                    R.drawable.cmcc_toolbar_del);
        menu.add(0, Menu.FIRST + 3, Menu.NONE, R.string._giveup).setIcon(
                R.drawable.cmcc_toolbar_cancel);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case Menu.FIRST + 1:
                saveInfo();
                break;
            case Menu.FIRST + 2:
                delete();
                break;
            case Menu.FIRST + 3:
                back();
                break;
        }
        return true;
    }

    /* ================== 设置button text 时间日期 ========================== */

    private void populateWhen() {
        long startMillis = mStartTime.toMillis(false /* use isDst */);
        long endMillis = mEndTime.toMillis(false /* use isDst */);
        setDate(mStartDateBtn, startMillis);
        setDate(mEndDateBtn, endMillis);
        setTime(mStartTimeBtn, startMillis);
        setTime(mEndTimeBtn, endMillis);
    }

    private void setDate(TextView view, long millis) {
        int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR
                | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_MONTH
                | DateUtils.FORMAT_ABBREV_WEEKDAY;
        view.setText(DateUtils.formatDateTime(this, millis, flags));
    }

    private void setTime(TextView view, long millis) {
        int flags = DateUtils.FORMAT_SHOW_TIME;
        if (DateFormat.is24HourFormat(this)) {
            flags |= DateUtils.FORMAT_24HOUR;
        }
        view.setText(DateUtils.formatDateTime(this, millis, flags));
    }

    /* ============================== 时间日期处理类 =========================== */

    private class DateClickListener implements View.OnClickListener {
        private Time mTime;

        public DateClickListener(Time time) {
            mTime = time;
        }

        public void onClick(View v) {
            new DatePickerDialog(ShowScreen.this, new DateListener(v), mTime.year, mTime.month,
                    mTime.monthDay).show();
        }
    }

    private class TimeClickListener implements View.OnClickListener {
        private Time mTime;

        public TimeClickListener(Time time) {
            mTime = time;
        }

        public void onClick(View v) {
            new TimePickerDialog(ShowScreen.this, new TimeListener(v), mTime.hour, mTime.minute,
                    DateFormat.is24HourFormat(ShowScreen.this)).show();
        }
    }

    private class DateListener implements OnDateSetListener {
        View mView;

        public DateListener(View view) {
            mView = view;
        }

        public void onDateSet(DatePicker view, int year, int month, int monthDay) {
            Time startTime = mStartTime;
            Time endTime = mEndTime;
            long startMillis;
            long endMillis;
            if (mView == mStartDateBtn) {
                int yearDuration = endTime.year - startTime.year;
                int monthDuration = endTime.month - startTime.month;
                int monthDayDuration = endTime.monthDay - startTime.monthDay;
                startTime.year = year;
                startTime.month = month;
                startTime.monthDay = monthDay;
                startMillis = startTime.normalize(true);
                endTime.year = year + yearDuration;
                endTime.month = month + monthDuration;
                endTime.monthDay = monthDay + monthDayDuration;
                endMillis = endTime.normalize(true);
            } else {
                startMillis = startTime.toMillis(true);
                endTime.year = year;
                endTime.month = month;
                endTime.monthDay = monthDay;
                endMillis = endTime.normalize(true);
                if (endTime.before(startTime)) {
                    endTime.set(startTime);
                    endMillis = startMillis;
                }
            }
            setDate(mStartDateBtn, startMillis);
            setDate(mEndDateBtn, endMillis);
            setTime(mEndTimeBtn, endMillis); // In case end time had to be reset
        }
    }

    private class TimeListener implements OnTimeSetListener {
        private View mView;

        public TimeListener(View view) {
            mView = view;
        }

        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            Time startTime = mStartTime;
            Time endTime = mEndTime;
            long startMillis;
            long endMillis;
            if (mView == mStartTimeBtn) {
                int hourDuration = endTime.hour - startTime.hour;
                int minuteDuration = endTime.minute - startTime.minute;
                startTime.hour = hourOfDay;
                startTime.minute = minute;
                startMillis = startTime.normalize(true);
                endTime.hour = hourOfDay + hourDuration;
                endTime.minute = minute + minuteDuration;
            } else {
                startMillis = startTime.toMillis(true);
                endTime.hour = hourOfDay;
                endTime.minute = minute;
                if (endTime.before(startTime)) {
                    endTime.monthDay = startTime.monthDay + 1;
                }
            }
            endMillis = endTime.normalize(true);
            setDate(mEndDateBtn, endMillis);
            setTime(mStartTimeBtn, startMillis);
            setTime(mEndTimeBtn, endMillis);
        }
    }
}
